package sbc.group1.lab1.alt;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.atomic.AtomicInteger;

import org.mozartspaces.core.MzsCoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.Signal;
import sun.misc.SignalHandler;

public class NotifyOn2000FinishedCars {
    private static final Logger log = LoggerFactory.getLogger(NotifyOn2000FinishedCars.class);
    private CarService cs;
        private volatile boolean running=true;
    private final AtomicInteger counter = new AtomicInteger();
    public static void main(String args[]) throws MalformedURLException, MzsCoreException, URISyntaxException, RemoteException, NotBoundException, InterruptedException {
        Signal.handle(new Signal("HUP"), 
                new SignalHandler() {
                    @Override
                    public void handle(Signal sig) {
                    }
                });
         new NotifyOn2000FinishedCars().run();
    }
        
    public NotifyOn2000FinishedCars() throws MalformedURLException, RemoteException, NotBoundException {
        cs= (CarService)
            Naming.lookup("rmi://localhost:1099/CarService");
    }
        
    public void run() throws InterruptedException, RemoteException, MalformedURLException, NotBoundException {
        RemoteListener on2000 = 
       new RemoteListener() {
            @Override
            public void onEvent(Object o) throws RemoteException {
                if (NotifyOn2000FinishedCars.this.counter.incrementAndGet()>=2000) {
                    cancel();
                    synchronized (NotifyOn2000FinishedCars.this) {
                        NotifyOn2000FinishedCars.this.notifyAll();
                    }
                }
            }
        };
        UnicastRemoteObject.exportObject(on2000,0);
        cs.registerAddListener(on2000,
        Containers.TOTALFINISHEDCARS);
        
        synchronized (this) {
            while (running) {
                wait();
            }
        }
        System.exit(0);
    }
    
    void cancel() {
        running=false;
    }
}
